package pro.syj.dao;

import java.sql.ResultSet;
import java.util.ArrayList;
import pro.syj.bean.Message;
import pro.syj.db.DBassist;

public class MessageDao {
	/*
	 * （管理员）查看所有评论
	 * return ArrayList<Message>
	 */
	public ArrayList<Message> selectAll(){
		
		ArrayList<Message> messagelist = new ArrayList<>();
		String sql = "select * from message";
		
		try{
			DBassist dbs = new DBassist();
			ResultSet rss = dbs.query(sql);
			while(rss != null && rss.next()){
				Message message = new Message();
				message.setId(rss.getInt(1));
				message.setSid(rss.getString(2));
				message.setSname(rss.getString(3));
				message.setContent(rss.getString(4));
				message.setTime(rss.getString(5));
				messagelist.add(message);
			}
		}catch(Exception e){
				e.printStackTrace();
		}
		
		return messagelist;
	}
	
	public ArrayList<Message> selectBySid(String sid){
		
		ArrayList<Message> messagelist = new ArrayList<>();
		String sql = "select * from message where sid = ?";
		
		try{
			DBassist dbs = new DBassist();
			ResultSet rss = dbs.query(sql,sid);
			while(rss != null && rss.next()){
				Message message = new Message();
				message.setId(rss.getInt(1));
				message.setSid(rss.getString(2));
				message.setSname(rss.getString(3));
				message.setContent(rss.getString(4));
				message.setTime(rss.getString(5));
				messagelist.add(message);
			}
		}catch(Exception e){
				e.printStackTrace();
		}
		
		return messagelist;
	}
	
	/*
	 * （学生）上传一条评论
	 * param sid sname context
	 * return int
	 */
	
	public int addMessage(String sid,String sname,String content){
		
		String sql = "insert into message(sid,sname,content,time) value(?,?,?,CURRENT_TIME)";
		int flag = -1;
		
		try{
			DBassist dbs = new DBassist();
			flag = dbs.update(sql, sid,sname,content);
			return flag;
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return flag;
	}
}
